<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/19
 * Time: 14:44
 */

namespace app\api\model;
use app\common\lib\wechat\WxCommon;
use think\Model;
use think\Log;
use think\Db;
use app\api\model\Coin as CoinModel;
use app\common\lib\exception\ApiException;

class Student extends Model
{
    /**
     * 获取学生账户余额信息
     * @param int $student_id 学生id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|false|\PDOStatement|string|Model
     */
    public function getStudentMoneyByStudentId($student_id){
        $info = $this
            ->where('student_id='.$student_id)
            ->field('coin,tuition')
            ->find();
        return $info;
    }

    /**
     * 查询单条信息
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getStudentInformation($user_id){
        $where = "stu.student_id=".$user_id;
        $info = $this
            ->alias('stu')
            ->join('user u', 'stu.student_id=u.id', 'LEFT')
            ->join('grade gra','stu.grade_id = gra.id','LEFT')
            ->join('address add','stu.student_id = add.member_id','LEFT')
            ->join('area area','add.area_code = area.code','LEFT')
            ->join('city city','area.citycode = city.code','LEFT')
            ->join('student_rank rank', 'stu.student_rank_id=rank.id', 'LEFT')
            ->field('stu.id,u.full_name,u.username,u.nickname,u.tel,u.sex,u.rec_bonus,u.pay_password,u.password,stu.tuition,stu.coin,stu.student_card_id,stu.student_id,stu.follow_les_id,stu.student_rank_id,rank.student_rank,stu.grade_id,gra.grade,add.address,add.area_code,city.name as city_name')
            ->where($where)
            ->find();
        if($info){
            $info = $info -> toArray();
        }
        return $info;
    }

    /**
     * 查询是否有每月奖励学币
     *@param receive_id int 用户id 必传
     * @author 巫玉梅 <1120504614@qq.com>
     * @return void
     */
    public function check_month_salary(){

        if (empty($_POST)) {
            throw new ApiException('数据不合法',404);
        }
        // receive_id int 用户id 必传
        if (empty($_POST['receive_id'])) {
            throw new ApiException('receive_id is not found',404);
        }
        Db::startTrans(); // 开启事务
        try {

            $info = Db::name('coin')
                ->where(array('receive_id' => $_POST['receive_id']))
                ->find();

                return show(config('code.success'),'ok',$info['month_coin']);

        } catch (\Exception $e) {
            Log::write($e->getMessage());
            Db::rollback(); // 事务回滚
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 领取每月学币
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getMonthCoin(){

        if (empty($_POST)) {
           throw new ApiException('数据不合法',404);
        }
        // receive_id int 用户id 必传
        if (empty($_POST['receive_id'])) {
            throw new ApiException('receive_id is not found',404);
        }
            Db::startTrans(); // 开启事务
        try {

            $info = Db::name('coin')
                ->where(array('receive_id' => $_POST['receive_id']))
                ->find();

            $student = Db::name('student')->where(array('student_id' => $_POST['receive_id']))->find();

            if ($info['month_coin'] != 0 && $info['month_coin_status'] == 0) {

                $coin['coin'] = $student['coin'] + $info['month_coin'];
                $student_coin = Db::name('student')->where(array('student_id' => $_POST['receive_id']))->update($coin);

                $coin = CoinModel::get(['receive_id' => $_POST['receive_id']]);
                $coin->month_coin = 0;
                $coin->month_coin_status = 1;
                $coin_result = $coin->save();

                if(!$coin_result){
                    return show(config('code.error'), 'coin表更改失败！');
                }

                if ($student_coin) {
                    //13位时间戳 加 4位随机数 如其他支付存在订单号则此订单号为该订单号 否则按当前
                    $coin_account['account_sn'] = date('YmdHis').rand(1000,9999);

                    $coin_account['user_id'] = $_POST['receive_id'];

                    $coin_account['cost_description'] = '领取奖励学币';

                    $coin_account['record_time'] = time();

                    $coin_account['cost_type'] = 1;  //1学币，2学费，3教师费用，4推荐奖金

                    $coin_account['cost'] = $info['month_coin'];

                    $coin_account['channel'] = 'backstage ';// 支付渠道 ali wx remain 支付宝 微信 余额

                    $result = Db::name('account')->insertGetId($coin_account);

                    if($result){

                        Db::name('account')->where('id',$result)->setField('status', '1');
                        Db::commit();//提交事务操作

                        SendMessage($_POST['receive_id'],'学币领取','您成功领取了每月奖励学币。');

                        return show(config('code.success'),'学币领取成功！',$info['month_coin']);

                    }else{
                        return show(config('code.error'),'流水记录失败！');
                    }
                } else {
                    return show(config('code.error'), '领取学币失败！');
                }
            } else {
                return show(config('code.error'), '暂无可领取的学币');
            }
        } catch (\Exception $e) {
            Log::write($e->getMessage());
            Db::rollback(); // 事务回滚
            throw new ApiException($e->getMessage(),500);
        }
    }


    /**
     * 根据学生用户id查询学生的信息
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function read(){
        $data = $_GET;
        if (empty($data)) {
           throw new ApiException('数据不合法',404);
        }
        //id int 用户id 必传
        if (empty($data['id'])) {
            throw new ApiException('id is not found',404);
        }
        try {
            
            $info = $this->getStudentInformation($data['id']);

            return show(config('code.success'), '获取数据成功', $info);

        } catch (\Exception $e) {
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * @ 学生添加关注的课程
     * @param id int 用户id 必传
     * @param lesson_id int 课程详情id 必传
     * @author 巫玉梅 <1120504614@qq.com>
     * @return ApiException|array|string|\think\response\Json
     */
    public function addFollowLesson(){

        $data = $_POST;
        if(empty($data)){
           throw new ApiException('数据不合法',404);
        }
        // id 用户id 必传
        if(empty($data['id'])){
            throw new ApiException('id is not found',404);
        }
        // 课程id 必传
        if(empty($data['lesson_id'])){
            throw new ApiException('lesson_id is not found',404);
        }
        try{
            $student = Db::name('student');

            // 查询是否有关注课程的记录
            $follow_lesson = Db::name('student')->where('student_id='.$data['id'])->find();

            // 获取关注课程的名称
            $lesson = Db::name("lesson")->where('id',$data['lesson_id'])->field("lesson_name")->find();

            if(empty($follow_lesson['follow_les_id'])){
                $str = $_POST['lesson_id'];
                $data1['follow_les_id'] = $str;
                $res = $student->where('student_id='.$data['id'])->update($data1);
                if($res){

                    SendMessage($data['id'],'课程关注','用户您好，您于'.date("Y-m-d H:i:s").'成功关注"'.$lesson['lesson_name'].'"课程');

                    return show(config('code.success'),'课程关注成功');
                }else{
                    return show(config('code.error'),'课程关注失败');
                }
            }else if(!empty($follow_lesson['follow_les_id'])){
                $arr = explode(',',$follow_lesson['follow_les_id']);
                if(in_array($_POST['lesson_id'],$arr)){
                    return show(config('code.error'),'该课程已关注,勿须重复关注');
                }else{
                    array_push($arr,$_POST['lesson_id']);
                    $str = implode(',',$arr);
                    $data1['follow_les_id'] = $str;
                    $res = $student->where('student_id='.$data['id'])->update($data1);
                    if($res){

                        SendMessage($data['id'],'课程关注','用户您好，您于'.date("Y-m-d H:i:s").'成功关注"'.$lesson['lesson_name'].'"课程。');

                        return show(config('code.success'),'课程关注成功');
                    }else{
                        return show(config('code.error'),'课程关注失败',[],500);
                    }
                }
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 学生取消关注的课程
     * @param id int 学生用户id 必传
     * @param lesson_id int 取消的课程详情id 必传
     * @author 巫玉梅 <1120504614@qq.com>
     * @return ApiException|array|string|\think\response\Json
     */
    public function cancelFollowLesson(){

        $data = $_POST;
        if(empty($data)){
           throw new ApiException('数据不合法',404);
        }
        // id int 学生用户id 必传
        if(empty($data['id'])){
            throw new ApiException('id is not found',404);
        }
        // lesson_id int 取消的课程详情id 必传
        if(empty($data['lesson_id'])){
            throw new ApiException('lesson_id is not found',404);
        }
        try{
            $student = Db::name('student');

            // 获取关注课程的名称
            $lesson = Db::name("lesson")->where('id',$data['lesson_id'])->field("lesson_name")->find();

            // 查询是否有关注课程的记录
            $follow_lesson = Db::name('student')->where('student_id='.$data['id'])->find();
            $arr = explode(',',$follow_lesson['follow_les_id']);

            if(in_array($data['lesson_id'],$arr)) {
                $res = '';
                foreach($arr as $key => $val){
                    if ($data['lesson_id'] == $arr[$key]) {
                        unset($arr[$key]);
                        $str = implode(',', $arr);
                        $data1['follow_les_id'] = $str;
                        $res = $student->where('student_id=' . $data['id'])->update($data1);
                    }else{

                    }
                }
                if ($res) {

                    SendMessage($data['id'],'课程取消','用户您好，您于'.date("Y-m-d H:i:s").'成功取消关注"'.$lesson['lesson_name'].'"课程。');

                    return show(config('code.success'), '取消关注成功');
                } else {
                    return show(config('code.error'), '取消关注失败');
                }
            }else if(!in_array($data['lesson_id'],$arr)){
                return show(config('code.error'),'无效请求！您没有关注该课程!',401);
            }
            //return
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }


    /**
     * @查询关注课程信息
     * @param Student_id int 学生用户id 必传
     * @author 巫玉梅 <1120504614@qq.com>
     * @return ApiException|array|string|\think\response\Json
     */
    public function seeAllCollectLesson(){

        $data = $_POST;
        if(empty($data)){
           throw new ApiException('数据不合法',404);
        }
        // Student_id  int 学生用户id 必传
        if(empty($data['student_id'])){
            throw new ApiException('student_id is not found',404);
        }

        try{

            $follow_lessons = Db::name('student')
                ->join('user','student_id = user.id','LEFT')
                ->field('student_id,user.full_name,follow_les_id')
                ->where('student_id='.$data['student_id'])
                ->find();

            $les_de_ids = explode(',',$follow_lessons['follow_les_id']);
            $les_de_id=array_reverse($les_de_ids);
            if(!empty($follow_lessons['follow_les_id'])) {
                foreach ($les_de_id as $key => $val) {

                    $lesson[] = Db::name('lesson')
                        ->alias("lesson")
                        ->join('subject','subject_id=subject.id','LEFT')
                        ->join('classroom','classroom_id=classroom.id','LEFT')
                        ->join('lesson_program','program_id=lesson_program.id','LEFT')
                        ->field('subject.subject,lesson_program.program,
                                classroom.classroom_address,lesson_sn,
                                cost_type,lesson_cost,lesson.id as lid,
                            lesson_program.program_full_name,lesson.lesson_name')
                        ->where('lesson.id=' . $les_de_id[$key])
                        ->find();

                }
                return show(config('code.success'),'获取数据成功',$lesson,200);
            }else{
                return show(config('code.error'),'没有关注信息，请求失败',[]);
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * @学生奖金转入学费
     * @param  student_id int 必传
     * @author 巫玉梅 <1120504614@qq.com>
     * @return ApiException|array|string|\think\response\Json
     */
    public function getTuitionByBonus(){
        if(empty($_POST)){
           throw new ApiException('数据不合法',404);
        }
        // student_id int 必传
        if(empty($_POST['id'])){
            throw new ApiException('id is not found',404);
        }
        Db::startTrans(); // 事务开启
        try{
            $id=$_POST['id'];
            $user = Db::name('user')
                ->where('id='.$id)
                ->find();
            if($user['rec_bonus'] > 0){
                $student = Db::name('student');
                $students = $student->where('student_id='.$id)->find();
                $data_rec_bonus['rec_bonus'] = 0;
                $data['tuition'] = $user['rec_bonus'] + $students['tuition'];

                $res = $student->where('student_id='.$id)->update($data);
                if($res){

                    $users = Db::name('user');
                    $result = $users->where('id='.$id)->update($data_rec_bonus);// 奖金账户清0

                    if($result){

                        $data1['account_sn'] =  date('YmdHis').rand(1000,9999);
                        $data1['account_type'] = 3;
                        $data1['user_id'] = $id;
                        $data1['cost_description'] = '推荐奖金转出到余额账户';
                        $data1['record_time'] = time();
                        $data1['cost_type'] = 4;
                        $data1['cost'] = -$user['rec_bonus'];
                        $data1['channel'] = 'backstage ';// 支付渠道 ali wx remain 支付宝 微信 余额
                        $data1['status'] = 1;

                        $res=Db::name('account')->insertGetId($data1);

                        if($res) {

                            $data2['account_sn'] =  date('YmdHis').rand(1000,9999);
                            $data2['account_type'] = 3;
                            $data2['user_id'] = $id;
                            $data2['cost_description'] = '推荐奖金转入到余额账户';
                            $data2['record_time'] = time();
                            $data2['cost_type'] = 2;
                            $data2['cost'] = $user['rec_bonus'];
                            $data2['channel'] = 'backstage ';// 支付渠道 ali wx remain 支付宝 微信 余额
                            $data2['status'] = 1;

                            $rec = Db::name('account')->insertGetId($data2);

                            if ($rec) {
                                Db::commit(); // 提交事务

                                SendMessage($id,'奖金转入','用户您好，您已成功将奖金转入到余额账户。');

                                return show(config('code.success'),'奖金转入成功');
                            } else {
                                Db::name('account')->where('id',$result)->setField('status', '0');
                                return show(config('code.error'),'录入学生推荐奖金转学费记录失败',[],500);
                            }
                        }else{
                            Db::name('account')->where('id',$result)->setField('status', '0');
                            return show(config('code.error'),'奖金转出流水记录失败！');
                        }
                    }else{
                        return show(config('code.error'),'奖金转入学费失败！');
                    }
                }else{
                    return show(config('code.error'),'奖金转入学费失败！',[],500);
                }
            }else{
                return show(config('code.error'),'你没有可转入学费余额的奖金');
            }
        }catch(\Exception $e){
            Log::write($e->getMessage());
            Db::rollback(); // 事务回滚
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * 学费提现
     * @param int user_id 用户id *必传
     * @param int bank_account_id 银行账户id *必传
     * @param float total_amount 提现金额 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function tuitionWithdrawals(){
        $request = $_POST;
        $wx = new WxCommon();

        /*$request['user_id'] = 1;
        $request['bank_full_name'] = '王柯';
        $request['bank_code'] = '1003';
        $request['bank_card'] = '6217003810062587293';
        $request['total_amount'] = 2;*/

        if(!isset($request['user_id'])){
            throw new ApiException('user_id（用户id） is not found！',404);
        }

        if(!isset($request['bank_account_id'])){
            throw new ApiException('bank_account_id（银行账户id） is not found！',404);
        }

        if(!isset($request['total_amount'])){
            throw new ApiException('total_amount（提现金额） is not found！',404);
        }

        if($request['total_amount'] < 1 || $request['total_amount'] > 5000000){
            return show(config('code.error'),'单笔提现必须大于等于0.01元且小于等于5万元！');
        }

        //用户银行账户信息
        $bank_account_info = db('bank_account')->where('user_id='.$request['user_id'].' AND id='.$request['bank_account_id'])->find();

        $request['bank_card'] = $bank_account_info['bank_card'];
        $request['bank_full_name'] = $bank_account_info['bank_full_name'];
        $request['bank_code'] = $bank_account_info['bank_code'];

        //用户可提现余额
        $user_info = db('student')->where('student_id='.$request['user_id'])->field('tuition,coin')->find();

        //提现手续费
        $service_cost = $wx::wxWithdrawalsServiceCost($request['total_amount']);

        if($request['total_amount'] / 100 > $user_info['tuition']){
            return show(config('code.error'),'输入的金额不正确！');
        }elseif(bcsub($user_info['tuition'],$request['total_amount'] / 100,2) < $service_cost / 100){
            return show(config('code.error'),'剩余余额不足以支付手续费 ¥ '.($service_cost / 100).',当前最大可提现金额为 ¥ '.(($user_info['tuition'] - $wx::wxWithdrawalsServiceCost($user_info['tuition'] * 100) / 100) < 0 ? 0 : ($user_info['tuition'] - $wx::wxWithdrawalsServiceCost($user_info['tuition'] * 100) / 100)),['total_amount' => ($user_info['tuition'] - $wx::wxWithdrawalsServiceCost($user_info['tuition'] * 100) / 100) < 0 ? 0 : ($user_info['tuition'] - $wx::wxWithdrawalsServiceCost($user_info['tuition'] * 100) / 100),'service_cost' => $service_cost],'10000');
        }

        //提现金额正确返回
        $return = [
            //当前提现金额
            'total_amount' => $request['total_amount'],

            //提示信息
            'service_cost' => $service_cost,
        ];

        //支付密码
        $pay_password = db('user')->where('id='.$request['user_id'])->field('pay_password')->find();

        if(empty($request['pay_password'])){
            return show(config('code.error'), '你还未输入支付密码！',$return,'10001');
        }

        if(md5($request['pay_password']) != $pay_password['pay_password']){
            return show(config('code.error'), '支付密码不正确！');
        }
        //halt($request);
        //生成流水号
        $request['account_sn'] = date('YmdHis').rand(1000,9999);

        //微信提现统一入口返回信息
        $array = \wxpay\request\WxWithdrawals::query($request);
        //halt($array);
        /*$array = [
            "return_code" =>  "SUCCESS",
            "return_msg" =>  "支付成功",
            "result_code" =>  "SUCCESS",
            "err_code" =>  "SUCCESS",
            "err_code_des" =>  "微信侧受理成功",
            "nonce_str" =>  "4c4vy9u74jfa40z0uj8gz23irnlsri5x",
            "mch_id" =>  "1505839931",
            "partner_trade_no" =>  "201806121445127027",
            "amount" =>  "1",
            "payment_no" =>  "10001005529192018061200000064540568",
            "cmms_amt" =>  "100",
        ];*/
        //提现判断
        if($array['return_code'] == 'SUCCESS'){

            if($array['result_code'] == 'FAIL'){

                return show(config('code.error'),$array['return_msg'].'！'.$array['err_code_des']);
            }else{

                $m = new Account();

                Db::startTrans();

                try{
                    //插入学费提现记录
                    $m::addAccount($request['account_sn'],$request['user_id'],'学费提现',-$array['amount'] / 100,2,'wx',2,1);

                    $sn = date('YmdHis').rand(1000,9999);
                    //插入学费提现扣除学币记录
                    $m::addAccount($sn,$request['user_id'],'学费提现扣除学币',-(($user_info['coin'] - ceil(($service_cost - $array['amount']) / 100 * (systemConfig('coin_tuition_ratio')))) <= 0 ? 0 : ceil(($service_cost - $array['amount']) / 100 * (systemConfig('coin_tuition_ratio')))),1,'backstage');

                    $money['tuition'] = $user_info['tuition'] - ($service_cost + $array['amount']) / 100;
                    $money['coin'] = ($user_info['coin'] - ceil(($service_cost - $array['amount']) / 100 * (systemConfig('coin_tuition_ratio')))) <= 0 ? 0 : $user_info['coin'] - ceil(($service_cost - $array['amount']) / 100 * (systemConfig('coin_tuition_ratio')));

                    $save = db('student')->where('student_id='.$request['user_id'])->update($money);

                    if($save){

                        //发送学费提现消息通知
                        SendMessage($request['user_id'],'学费提现',date('Y-m-d H:i:s').'申请学费提现成功！ 订单号【'.$request['account_sn'].'】请留意银行卡到账记录或在我的流水记录查询！提现手续费 '.($array['cmms_amt']/100).' 元');

                        //发送学费提现扣除学币消息通知
                        SendMessage($request['user_id'],'学费提现扣除学币',date('Y-m-d H:i:s').'学费提现扣除学币 订单号【'.$sn.'】');

                        Db::commit();

                        return show(config('code.success'),'申请提现成功！');
                    }else{
                        return show(config('code.error'),'申请提现失败！');
                    }
                }catch(\Exception $e){

                    Log::write($e->getMessage()."\r\n".json_encode($array));
                    Db::rollback();
                    throw new ApiException($e->getMessage(),500);
                }
            }
        }else{
            return show(config('code.error',$array['return_msg']));
        }
    }

}